package com.spring.demo01;

import com.spring.demo01.config.MyConfiguration;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Iterator;

/**
 * 注解方式创建bean，使用bean
 * url: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html
 */
public class App2 {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.register(MyConfiguration.class);
		context.refresh();
		MyService bean = context.getBean(MyService.class);
		String item = bean.getItem();
		System.out.println(item);

		//获取工厂
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();

		//使用工厂手动创建单例
		beanFactory.registerSingleton("myservice2",new MyService("hello222"));
		MyService myservice2 = context.getBean("myservice2", MyService.class);

		String item1 = myservice2.getItem();
		System.out.println("second:---->");
		System.out.println(item1);

		//打印工厂都创建了什么Bean
		Iterator<String> beanNamesIterator = beanFactory.getBeanNamesIterator();
		while(beanNamesIterator.hasNext()){
			String next = beanNamesIterator.next();
			System.out.println(next);
		}
	}
}
